﻿namespace CommLibrary.Http
{
    using Newtonsoft.Json;
    using System;
    using System.IO;
    using System.Net;
    using System.Net.Http.Headers;
    using System.Text;

    namespace HttpHelperNamespace
    {
        public class HttpHelper
        {
            public static readonly HttpClient _client = new HttpClient();

            public static HttpHelper Init()
            {
                return new HttpHelper();
            }


            /// <summary>
            /// 向指定 URL 发送POST方法的请求
            /// </summary>
            /// <param name="url">发送请求的 URL</param>
            /// <param name="jsonData">请求参数，请求参数应该是Json格式字符串的形式。</param>
            /// <returns>所代表远程资源的响应结果</returns>
            public static T SendPost<T>(string url, object jsonData, WebHeaderCollection webHeader = null)
            {
                string result = String.Empty;
                try
                {
                    // 创建HttpWebRequest对象
                    HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
                    // 设置Post调用方法
                    httpRequest.Method = "Post";
                    //设置参数传输类型
                    httpRequest.ContentType = "application/json;";
                    if (webHeader != null)
                    {
                        httpRequest.Headers = webHeader;
                    }

                    //传输参数格式转换
                    httpRequest.ContentLength = Encoding.UTF8.GetByteCount(JsonConvert.SerializeObject(jsonData));
                    Stream myRequestStream = httpRequest.GetRequestStream();
                    StreamWriter sw = new StreamWriter(myRequestStream);
                    sw.Write(JsonConvert.SerializeObject(jsonData));
                    sw.Close();

                    // HttpWebRequest发起调用
                    using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
                    {
                        // StreamReader对象
                        StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                        // 返回结果
                        string responseString = sr.ReadToEnd();

                        if (!string.IsNullOrWhiteSpace(responseString))
                        {
                            return JsonConvert.DeserializeObject<T>(responseString);
                        }
                        else
                        {
                            return default;
                        }
                    }
                }
                catch (Exception s)
                {
                    //返回错误信息
                    throw new Exception("接口请求异常：" + s.Message);
                }
            }




            /// <summary>
            /// Get请求
            /// </summary>
            /// <param name="url"></param>
            /// <param name="headers"></param>
            /// <returns></returns>
            public async Task<string> GetAsync(string url, Dictionary<string, string> headers = null)
            {
                return await SendRequestAsync(HttpMethod.Get, url, headers);
            }

            /// <summary>
            /// Post请求
            /// </summary>
            /// <param name="url"></param>
            /// <param name="content"></param>
            /// <param name="headers"></param>
            /// <returns></returns>
            public async Task<string> PostAsync(string url, string content, Dictionary<string, string> headers = null)
            {
                var stringContent = new StringContent(content, Encoding.UTF8, "application/json");
                return await SendRequestAsync(HttpMethod.Post, url, headers, stringContent);
            }

            /// <summary>
            /// Put请求
            /// </summary>
            /// <param name="url"></param>
            /// <param name="content"></param>
            /// <param name="headers"></param>
            /// <returns></returns>
            public async Task<string> PutAsync(string url, string content, Dictionary<string, string> headers = null)
            {
                var stringContent = new StringContent(content);
                return await SendRequestAsync(HttpMethod.Put, url, headers, stringContent);
            }

            /// <summary>
            /// Delete请求
            /// </summary>
            /// <param name="url"></param>
            /// <param name="headers"></param>
            /// <returns></returns>
            public async Task<string> DeleteAsync(string url, Dictionary<string, string> headers = null)
            {
                return await SendRequestAsync(HttpMethod.Delete, url, headers);
            }
            /// <summary>
            /// 请求
            /// </summary>
            /// <param name="method"></param>
            /// <param name="url"></param>
            /// <param name="headers"></param>
            /// <param name="content"></param>
            /// <returns></returns>
            /// <exception cref="Exception"></exception>
            private async Task<string> SendRequestAsync(HttpMethod method, string url, Dictionary<string, string> headers, HttpContent content = null)
            {
                try
                {
                    var request = new HttpRequestMessage(method, url);

                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {

                            if (header.Key == "Authorization")
                            {
                                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", header.Value);
                            }
                            else
                            {
                                request.Headers.Add(header.Key, header.Value);
                            }

                        }
                    }

                    if (content != null)
                    {
                        request.Content = content;
                    }

                    var response = _client.Send(request);

                    if (response.IsSuccessStatusCode)
                    {
                        return await response.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        return ($"请求失败，状态码为: {response.StatusCode}");
                    }
                }
                catch (Exception ex)
                {
                    return ($"在 HTTP 请求期间发生错误： {ex.Message}");
                }
            }


        }
    }
}
